package com.msg.test.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.DataOutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MsgUtil {
    private static int sequenceId=0;
    private static Log log = LogFactory.getLog(MsgUtil.class);

    public synchronized static int getSequence(){
        ++sequenceId;
        if (sequenceId>255){
            sequenceId = 0;
        }
        return sequenceId;
    }

    public static byte[] getMsgBytes(byte[] msg,int start,int end){
        byte[] msgByte = new byte[end - start];
        int j = 0;
        for (int i = start; i < end;i++){
            msgByte[j] = msg[i];
            j++;
        }
        return msgByte;
    }

    public static void writeString(DataOutputStream dos,String msg,int length){
        try {
            byte[] data = msg.getBytes("gb2312");
            if (data.length > length){
                log.error("向流中写入的数据长度过长，此字符串为"+msg);
            }
            int srcLen = data.length;
            dos.write(data);
            while (srcLen < length){
                dos.write('\0');
                srcLen++;
            }
        }catch (Exception ex){
            log.error("向流中写入字符串失败："+ex.getMessage());
        }
    }

    public static String getTimestamp(){
        DateFormat format = new SimpleDateFormat("MMddhhmmss");
        return format.format(new Date());
    }

    public static byte[] getAuthenticatorSource(String spId,String shareSecret,String timestamp){
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] data = (spId+"\0\0\0\0\0\0\0\0\0"+shareSecret+timestamp).getBytes();
            return md5.digest(data);
        }catch (NoSuchAlgorithmException ex){
            log.error("sp链接拼接AuthenticatorSource失败"+ex.getMessage());
            return null;
        }
    }
}
